package com.wanshu.controller;


import com.alibaba.fastjson.JSON;
import com.wanshu.entity.User;
import com.wanshu.entity.vo.UserInfo;
import com.wanshu.service.UserService;
import com.wanshu.util.ImageUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@RestController
@CrossOrigin("http://localhost:8080")
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @RequestMapping("/findAll")
    public String findAll() throws IOException {
        List<User> all = userService.findAll();
        return JSON.toJSONString(all);
    }

    @RequestMapping("/getUserInfo/{id}")
    public UserInfo getUserInfo(@PathVariable String id){
        return userService.getUserInfo(Integer.valueOf(id));
    }

    @RequestMapping("/register")
    public void register(@RequestBody User user){
        System.out.println(user.toString());
        System.out.println(user.getNickname());
        this.userService.insert(user);
    }
    @RequestMapping("/login")
    public String login(@RequestBody User user){
        System.out.println(user.toString());
        User login = userService.login(user);
        System.out.println(login);
        return JSON.toJSONString(login);
    }
//    @RequestMapping("/uploadHeadImage")
//    public String uploadHeadImage(User user){
//        System.out.println(user.getHeadImage());
//        Boolean aBoolean = userService.uploadHeadImage(user);
//        if(aBoolean){
//            return "上传成功!";
//        }
//        return null;
//    }
    @PostMapping("/uploadAvatar")
    public String uploadAvatar(@RequestParam("file") MultipartFile file, HttpSession session) {
        try {
            // 假设用户名在会话中保存
            System.out.println("贵在坚持");
            System.out.println(file);
            session.getAttribute("username");
            String filePath = ImageUtil.upload(file, session);

            // 将文件路径存入数据库（假设你有一个方法来更新用户头像路径）
            userService.updateUserAvatar(filePath);

            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
    }

    @RequestMapping("/update")
    public String update(User user){
        Integer update = userService.update(user);
        String message = "修改失败!";
        if(update > 0){
            return "修改成功!";
        }
        return message;
    }
}
